import { createStore, createLogger } from "vuex";
import { ListItem } from "../views/home/types";

interface RootState {
  car: CarItem[];
}

interface CarItem extends ListItem {
  count: number;
  isChecked: boolean;
}

export default createStore<RootState>({
  state: {
    car: [],
  },
  mutations: {
    // 添加购物车
    addCar(state, payload: ListItem) {
      // 查找数据
      const item = state.car.find((v) => v.id === payload.id);
      // 验证数据是否存在
      if (item) {
        // 存在++
        item.count++;
      } else {
        // 不存在
        // 推入新数据
        state.car.push({
          ...payload,
          count: 1,
          isChecked: false,
        });
      }
    },
  },
  actions: {},
  modules: {},
  plugins: [createLogger()],
});
